package com.baocaiqiche.dev.taoforandroid;


import android.os.Handler;
import android.os.Looper;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HttpUtils {

    private OkHttpClient client ;
    private Handler mHandler ;

    public HttpUtils(){
        client = new OkHttpClient();
        mHandler = new Handler(Looper.getMainLooper());
    }

    public void getRequest(String url, StringCallBack callBack){
        Request request = new Request.Builder().url(url).build();
        deliveryResult(callBack,request);
    }

    public void postRequest(String url , ArrayList<Param> paramArrayList , StringCallBack callBack){

        FormBody.Builder builder = new FormBody.Builder();

        if(paramArrayList.size() > 0){
            for (Param param : paramArrayList){
                builder.add(param.key,param.value);
            }
        }

        FormBody requestBody = builder.build();
        Request request = new Request.Builder().url(url).post(requestBody).build();

        deliveryResult(callBack,request);
    }

    private void deliveryResult(final StringCallBack callBack, Request request)
    {
        client.newCall(request).enqueue(new Callback()
        {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onFailure(call.request(),e);
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                mHandler.post(new Runnable() {
                    @Override
                    public void run()
                    {
                        try {
                            String string = response.body().string();
                            if(callBack != null){
                                callBack.onResponse(string);
                            }
                        } catch (IOException e) {
                            callBack.onFailure(response.request(),e);
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

    public interface StringCallBack{
        void onFailure(Request request, IOException e) ;
        void onResponse(final String response) throws IOException;
    }

    public static class Param
    {
        String key;
        String value;

        public Param(String key, String value)
        {
            this.key = key;
            this.value = value;
        }
    }
}
